package com.candoit.webapps.pricing.listeners;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.behavior.AjaxBehavior;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;

import com.candoit.webapps.pricing.model.CentroCostos;
import com.candoit.webapps.pricing.model.CentroCostosCriterio;
import com.candoit.webapps.pricing.model.CriterioDistribucion;
import com.candoit.webapps.pricing.util.QueryUtil;


@ViewScoped
public class ChangeListener implements ValueChangeListener {  
	public void processValueChange(ValueChangeEvent event)
			throws AbortProcessingException {
		 UIComponent c = (UIComponent) event.getSource();  
		 String[] ids = c.getId().split("_");
		 Object oldValue = event.getOldValue();
	     Object newValue = event.getNewValue();
	      if (oldValue != newValue)
	        {	
	           Double cantidad = (Double)newValue;   
	           Double totalAsignadoExceptsCC = QueryUtil.getInstance().getTotalAsignadoCriterioExceptsCC(Integer.valueOf(ids[1]), Integer.valueOf(ids[2]));
	           Double totalAsignado = cantidad + totalAsignadoExceptsCC;
	           CentroCostos centro = QueryUtil.getInstance().getCentroById(Integer.valueOf(ids[2]));
	           CriterioDistribucion criterio = QueryUtil.getInstance().getCriterioDistribucionById(Integer.valueOf(ids[1]));
	           CentroCostosCriterio centroCriterio = QueryUtil.getInstance().getCentroCostosCriterioObject(centro, criterio);
	           centroCriterio.setCantidad(cantidad);
	           DecimalFormat twoDForm = new DecimalFormat("#.##");
	           double perc = centroCriterio.getCantidad()* 100 / totalAsignado;
	           c.findComponent("porc_" + ids[1] + "_"  + ids[2]).getAttributes().put("value", twoDForm.format(perc));
	           c.findComponent("criterio_"  + ids[1]).getAttributes().put("value", twoDForm.format(totalAsignado));
	        }        
		
	}  
}  



